import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Auth } from './entities/auth.entity';
import { Repository } from 'typeorm';
import * as bcryptjs from "bcryptjs"
import { JwtService } from "@nestjs/jwt"
import { ApiBearerAuth } from '@nestjs/swagger';

@Injectable()
@ApiBearerAuth()
export class AuthService {
  constructor(@InjectRepository(Auth) private readonly user: Repository<Auth>,
    private readonly JwtService: JwtService) { }
  // 注册
  async signup(signupData: CreateAuthDto) {
    const findUser = await this.user.findOne({
      where: { username: signupData.username }
    })
    if (findUser && findUser.username === signupData.username) throw new HttpException('用户已存在', HttpStatus.BAD_REQUEST);
    // 对密码进行加密处理
    signupData.password = bcryptjs.hashSync(signupData.password, 10)
    await this.user.save(signupData)
    return "注册成功"
  }

  // 登录
  // 登录
  async login(loginData: CreateAuthDto) {

    const findUser = await this.user.findOne({
      where: { username: loginData.username }
    })
    // 没有找到
    if (!findUser) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);

    // 找到了对比密码
    const compareRes: boolean = bcryptjs.compareSync(loginData.password, findUser.password)
    // 密码不正确
    if (!compareRes) throw new HttpException('密码不正确', HttpStatus.UNAUTHORIZED);
    const payload = { username: findUser.username }

    return {
      access_token: this.JwtService.sign(payload),
      msg: "登录成功"
    }
  }

}
